<?php
    /**
     * HTML editor (based on elRTE/elFinder)
     * 
     * @author Anton Perkin
     * @package DevTools
     * @version 1.0
     *
     */
    class HtmlEditor
    {
        /* VARIABLES */

    	/**
    	 * Editor container id
    	 *
    	 * @var string
    	 */
    	public $containerId = 'editorContainer';

    	/**
    	 * Container CSS styles
    	 *
    	 * @var string
    	 */
    	public $containerStyle = '';

    	/**
    	 * File manager title
    	 *
    	 * @var string
    	 */
    	public $fileManagerTitle = 'Files';
    	
    	/**
    	 * TODO: Path to files
    	 *
    	 * @var string
    	 */
    	private $pathToFiles = '../../../../../languages/english/html/';

    	/**
    	 * TODO: URL to files
    	 *
    	 * @var string
    	 */
    	private $urlToFiles = 'http://qa/app/includes/languages/english/html/';
    	
    	/**
    	 * Editor options
    	 * Available options list: http://elrte.org/redmine/projects/elrte/wiki/Docs_EN#Options
    	 *
    	 * @var array
    	 */
    	private $options = array();

    	/**
    	 * File manager options
    	 * Available options list: http://elrte.org/redmine/projects/elfinder/wiki/Client_Configuration_EN#Options
    	 *
    	 * @var array
    	 */
    	private $fmOptions = array();
    	
    	/**
    	 * CSS files array
    	 *
    	 * @var array
    	 */
    	private $cssFiles = array();
    	
    	/**
    	 * Text to appear inside the editor
    	 *
    	 * @var string
    	 */
    	public $text = '';
    	
    	
        /* CONSTRUCTORS */

        /**
         * Default constructor
         */
    	function __construct ()
    	{
			$this->SetDefaultOptions();
    	}

    	
    	/* PRIVATE METHODS */
    	
    	/**
    	 * Sets default options
    	 *
    	 */
    	private function SetDefaultOptions()
    	{
    		$this->AddOption('lang', "'ru'");
    		$this->AddOption('cssClass', "'el-rte'");
    		$this->AddOption('height', 500);
    		$this->AddOption('toolbar', "'maxi'");
    		$this->AddOption('styleWithCSS', "true");
    		$this->AddOption('fmAllow', "true");
    		$this->AddOption('fileManagerTitle', "'Files'");
    	}
    	
    	/**
    	 * Gets editor component path
    	 * 
    	 * @return string
    	 *
    	 */
    	private function GetEditorPath()
    	{
    		return dirname(str_replace(strtolower(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT'])), '', strtolower(str_replace('\\', '/', __FILE__)))).'/htmleditor/';
    	}
    	
        /**
    	 * Editor initialization
    	 */
    	private function Initialize()
    	{
    		//path
    		$path = '/./'.$this->GetEditorPath();
    		
    		echo "
				<!-- jQuery and jQuery UI -->
				<script src='{$path}js/jquery-1.6.1.min.js' type='text/javascript' charset='utf-8'></script>
				<script src='{$path}js/jquery-ui-1.8.13.custom.min.js' type='text/javascript' charset='utf-8'></script>
				<script src='{$path}js/jquery.loading.js' type='text/javascript' charset='utf-8'></script>
				<link rel='stylesheet' href='{$path}css/smoothness/jquery-ui-1.8.13.custom.css' type='text/css' media='screen' charset='utf-8'>
				<link rel='stylesheet' href='{$path}css/jquery.loading.css' type='text/css' media='screen' charset='utf-8'>
				
				<!-- elRTE -->
				<script src='{$path}js/elrte.min.js' type='text/javascript' charset='utf-8'></script>
				<link rel='stylesheet' href='{$path}css/elrte.min.css' type='text/css' media='screen' charset='utf-8'>
			
				<!-- elRTE translation messages -->
				<script src='{$path}js/i18n/elrte.".$this->GetOption('lang').".js' type='text/javascript' charset='utf-8'></script>
			";
    		
    		//file manager initialization
    		$this->InitializeFileManager($path);
    		
    	    //editor initialization
    	    $jsCode = "
				<script type='text/javascript' charset='utf-8'>
					$().ready(function()
					{
						var opts = {
			";
    	    
    	    //options
    	    foreach ($this->options as $name => $value)
    	    {
    	    	$jsCode .= "$name: $value,";
    	    } 	    
    	    
    	    //options
    	    $fmOptionsString = '';
    	    foreach ($this->fmOptions as $fmOptionName => $fmOptionValue)
    	    {
    	    	$fmOptionsString .= "$fmOptionName: $fmOptionValue,";
    	    }  

    	    //file manager integration
    	    $jsCode .= "
			    fmOpen : function(callback) {
			       $('<div id = \"{$this->containerId}_fm\"></div>').elfinder
			       ({
			          url : '".$this->GetEditorPath()."filemanager/connectors/php/connector.php',
			          lang : ".self::GetOption('lang').",
			          cutURL: 'http://".$_SERVER['HTTP_HOST']."',
			          closeOnEditorCallback : true,
			          editorCallback : FileContentToEditor,
			          $fmOptionsString
			          dialog : { width : 900, modal : true, title : '".$this->fileManagerTitle."' } // open in dialog window
			       })
			    }    	    
    	    ";

    	    //show editor
    	    $jsCode .= " 
						}
						$('#{$this->containerId}').elrte(opts);
					})
			";
    	    
    	    //file manager JS functions
			$jsCode .= "		
					//loads the data from file manager into HTML editor
					function FileContentToEditor(url)
					{
						$.get(url, function(data) {
							$('#{$this->containerId}').elrte('val', data);
						});
						$('#{$this->containerId}_filename').val(url);
    				}
    				
    				//executes after save is complete
    				function AfterSave(data)
    	    		{
    	    			$.loading();
    	    			if (data == '')
    	    			{
							$('#{$this->containerId}_save_error').dialog();
    	    				$('#{$this->containerId}_save_error').dialog('open');
    					}
    				}
    		";
			
			//AJAX loading module initialization
    		$jsCode .= "		
					$.loading.classname = 'loading-text';
					$.loading.text = 'Saving...';

				</script>";
    	    
    	    echo $jsCode;
    	}
    	
    	/**
    	 * Initializes file manager
    	 *
    	 * @param string $path path to the HTML editor
    	 */
    	private function InitializeFileManager($path)
    	{
    		//fm path
    		$path = $path.'filemanager/';
    		
    		//JS and CSS files
    		echo "
    			<!-- elFinder -->
				<script src='{$path}js/elfinder.min.js' type='text/javascript' charset='utf-8'></script>
				<link rel='stylesheet' href='{$path}css/elfinder.css' type='text/css' media='screen' charset='utf-8'>
				<script src='{$path}js/i18n/elfinder.".$this->GetOption('lang').".js' type='text/javascript' charset='utf-8'></script>
    		";
    		
    		//DEPRICATED. Used when file manager is a separate component
    		//files
//			<script src='{$path}js/jquery.js' type='text/javascript' charset='utf-8'></script>
//			<script src='{$path}js/jquery-ui-1.7.2.custom.min.js' type='text/javascript' charset='utf-8'></script>
//			<link rel='stylesheet' href='{$path}js/ui-themes/base/ui.all.css' type='text/css' media='screen' charset='utf-8'>    	
    		//initialize
//    		echo '
//				<script type="text/javascript" charset="utf-8">
//					$().ready({
//						$("#'.$this->containerId.'_filemanager").elfinder({
//							url : "'.$path.'connectors/php/connector.php",
//							lang : "'.str_replace("'", '', $this->GetOption("lang")).'"
//				    	})
//					})
//				</script>
//    		';
    	}
    	
    	
    	/* PUBLIC METHODS */
	
    	/**
    	 * Adds an option
    	 * Available options list: http://elrte.org/redmine/projects/elrte/wiki/Docs_EN#Options
    	 *
    	 * @param string $name option name
    	 * @param mixed $value option value
    	 */
    	public function AddOption($name, $value)
    	{
    		$this->options[$name] = $value;
    	}
    	
    	/**
    	 * Gets option value
    	 *
    	 * @param string $optionName option name
    	 */
    	public function GetOption($optionName)
    	{
    		return $this->options[$optionName];
    	}

        /**
    	 * Adds options
    	 * Available options list: http://elrte.org/redmine/projects/elrte/wiki/Docs_EN#Options
    	 *
    	 * @param array $options options
    	 */
    	public function AddOptions(array $options)
    	{
    		foreach ($options as $name => $value)
    		{
    			$this->options[$name] = $value;
    		}
    	}

        	/**
    	 * Adds a file manager option
    	 * Available options list: http://elrte.org/redmine/projects/elfinder/wiki/Client_Configuration_EN#Options
    	 *
    	 * @param string $name option name
    	 * @param mixed $value option value
    	 */
    	public function AddFMOption($name, $value)
    	{
    		$this->options[$name] = $value;
    	}
    	
    	/**
    	 * Gets file manager option value
    	 *
    	 * @param string $optionName option name
    	 */
    	public function GetFMOption($optionName)
    	{
    		return $this->fmOptions[$optionName];
    	}    	
    	
        /**
    	 * Adds file manager options
    	 * Available options list: http://elrte.org/redmine/projects/elfinder/wiki/Client_Configuration_EN#Options
    	 *
    	 * @param array $options options
    	 */
    	public function AddFMOptions(array $options)
    	{
    		foreach ($options as $name => $value)
    		{
    			$this->fmOptions[$name] = $value;
    		}
    	}    	
    	
        /**
    	 * Adds CSS files
    	 *
    	 * @param array $files CSS files array
    	 */
    	public function AddCSSFiles(array $files)
    	{
    		if (empty($files)) return false;
    		
    		//generate CSS files option
			$this->cssFiles = $files;
			$cssFilesString = '[';
			foreach ($files as $file)
			{
				$cssFilesString .= "'".$file."',";
			}
			$cssFilesString = substr_replace($cssFilesString, '', strrpos($cssFilesString, ','), 1);
			$cssFilesString .= ']';
			
			//add CSS files option
			$this->AddOption('cssfiles', $cssFilesString);
    	}    	
    	
    	/**
    	 * Displays the editor
    	 *
    	 */
    	public function Display()
    	{
    		//initialize editor and file manager
		    $this->Initialize();
    		
		    //form action
    		$formAction = $this->GetEditorPath().'post.php';
    		
    		//editor form
		    echo '
		    	<form method = "POST" onsubmit = "$.loading(); $.post(\''.$formAction.'\', {contents: $(\'#'.$this->containerId.'\').elrte(\'val\'), filename: $(\'#'.$this->containerId.'_filename\').val() }, AfterSave); return false; ">
		    		<div id = "'.$this->containerId.'" style = "'.$this->containerStyle.'"><p></p>'.$this->text.'</div>
		    		<input name = "filename" id = "'.$this->containerId.'_filename" type = "hidden" />
		    	</form>';
		    
		    //error messages
		    echo "<div title = 'Error' id = '{$this->containerId}_save_error' style = 'display: none; '>File doesn't exist</div>";
    	}
    }
?>